<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>promise封装ajax</title>
</head>

<body>
  <script>
    // promise封装ajax
    function promiseAjaxFn(method, url) {
      let promise = new Promise((resolve, reject) => {
        let xhr;
        if (window.XMLHttpRequest) {
          //非IE
          xhr = new XMLHttpRequest();
        } else {
          //IE
          xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open(method, url, true);
        // 设置响应的数据类型
        xhr.responseType = "json";
        // 设置请求头信息
        xhr.setRequestHeader("Accept", "application/json");
        xhr.onreadstatechange = () => {
          if (xhr.readState == 4) {
            if (xhr.status == 200) {
              resolve(JSON.parse(xhr.responseText));
            } else {
              reject(xhr.responseText);
            }
          }
        };

        xhr.send(null);
      });
      return promise;
    }
  </script>
</body>

</html>